package com.sdl3.render;

import com.sdl3.shape.PineaRect;
import com.sun.jna.Pointer;

public class PineaImage {

    private Pointer imagePointer;
    private PineaRect region;
    private float scaleX;
    private float scaleY;
    private double angle;
    private int flip;

    private static final int PINEA_FLIP_HORIZONTAL = 1;
    private static final int PINEA_FLIP_VERTICAL = 2;

    public PineaImage(Pointer imagePointer, PineaRect region) {
        this.imagePointer = imagePointer;
        this.region = region;
        this.scaleX = 1.0f;
        this.scaleY = 1.0f;
        this.angle = 0.0;
        this.flip = 0;
    }

    public Pointer getData() {
        return imagePointer;
    }

    public int getWidth() {
        return (int) region.w;
    }

    public int getHeight() {
        return (int) region.h;
    }

    public PineaRect getRegion() {
        return region;
    }

    public float getScaleX() {
        return scaleX;
    }

    public float getScaleY() {
        return scaleY;
    }

    public double getAngle() {
        return angle;
    }

    public int getFlip() {
        return flip;
    }

    public PineaImage scale(float x, float y) {
        PineaImage image = copyImage(this);
        image.scaleX = x;
        image.scaleY = y;
        return image;
    }

    public PineaImage rotate(double angle) {
        PineaImage image = copyImage(this);
        image.angle = angle;
        return image;
    }


    public PineaImage flip(boolean flipX, boolean flipY) {
        PineaImage image = copyImage(this);
        if (!flipX && !flipY) {
            return image;
        }
        int flip = 0;
        if (flipX) {
            flip |= PINEA_FLIP_HORIZONTAL;
        }
        if (flipY) {
            flip |= PINEA_FLIP_VERTICAL;
        }
        image.flip = flip;
        return image;
    }

    public PineaImage crop(int x, int y, int width, int height) {
        PineaImage image = copyImage(this);
        image.region.x = x;
        image.region.y = y;
        image.region.w = width;
        image.region.h = height;
        return image;
    }

    private PineaImage copyImage(PineaImage source) {
        PineaRect region = new PineaRect(source.region.x, source.region.y, source.region.w, source.region.h);
        PineaImage image = new PineaImage(source.imagePointer, region);
        image.scaleX = source.scaleX;
        image.scaleY = source.scaleY;
        image.angle = source.angle;
        image.flip = source.flip;
        return image;
    }
}
